#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <functional>
#include <unordered_map>
#include "nocopy.hpp"
#include "Comm.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"

const static unsigned int default_backlog = 5;
using task_t = std::function<void()>;
using callback_t = std::function<void(int, InetAddr &)>;

class TcpServer : nocopy
{
public:
    TcpServer(uint16_t port) : _port(port), _isrunning(false)
    {
    }

    ~TcpServer()
    {
    }

    void Init()
    {
        // 创建套接字
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            lg.LogMessage(Error, "create socket failed, errno %d is %s\n", errno, strerror(errno));
            exit(SOCKET_ERROR);
        }
        int opt = 1;
        setsockopt(_listensock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        lg.LogMessage(Debug, "create socket success, sockfd: %d\n", _listensock);
        // 填写服务器结构体信息并绑定
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_port = htons(_port);
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = htonl(INADDR_ANY);

        if (bind(_listensock, CONV(&local), sizeof(local)) != 0)
        {
            lg.LogMessage(Error, "bind failed, errno is %d : %s\n", errno, strerror(errno));
            exit(BIND_ERROR);
        }
        // 绑定成功将套接字设置为监听状态
        lg.LogMessage(Debug, "socket bind success, sockfd is %d\n", _listensock);
        if (listen(_listensock, default_backlog) != 0)
        {
            lg.LogMessage(Error, "listen socket failed, errno %d is %s\n", errno, strerror(errno));
            exit(LISTEN_ERROR);
        }
        lg.LogMessage(Debug, "listen socket success, sockfd is %d\n", _listensock);
        ThreadPool<task_t>::GetInstance()->Start();
        _funcs.insert(std::make_pair("defaultservice", std::bind(&TcpServer::DefaultService, this, std::placeholders::_1, std::placeholders::_2)));
    }

    void Service(int sockfd)
    {
        
    }

    void DefaultService(int sockfd, InetAddr &addr)
    {
        (void)addr;
        std::string func_list = "| ";
        for (auto list : _funcs)
        {
            func_list += list.first;
            func_list += " | ";
        }
        ssize_t n = write(sockfd, func_list.c_str(), func_list.size());
        if (n < 0)//发送错误
        {
            lg.LogMessage(Error, "write failed, errno %d is %s", errno, strerror(errno));
            exit(WRITE_ERROR);
        }
        else if (n == 0)
        {
            lg.LogMessage(Info, "client quit..\n");
            exit(WRITE_ERROR);
        }
    }

    std::string Read(int sockfd)
    {
        char buffer[1024];
        ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
        }
        else if (n == 0) // 客户端读端关闭
        {
            lg.LogMessage(Info, "client quit...\n");
        }
        else
        {
            lg.LogMessage(Error, "write failed, errno %d is %s", errno, strerror(errno));
            exit(WRITE_ERROR);
        }
        return buffer;
    }

    void Routine(int sockfd, InetAddr addr)
    {
        // 服务端基础服务，发送业务菜单给客户端
        _funcs["defaultservice"](sockfd, addr);
        std::string type = Read(sockfd);
        auto pos = _funcs.find(type);
        if (pos == _funcs.end())//not find
            type = "unknown";
        _funcs[type](sockfd, addr);
        close(sockfd);
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            // 接受新的连接请求
            int sockfd = accept(_listensock, CONV(&client), &len);
            if (sockfd < 0)
            {
                lg.LogMessage(Warning, "accept failed, errno %d is %s\n", errno, strerror(errno));
                continue;
            }
            else
            {
                lg.LogMessage(Debug, "accept success, get a new sockfd is %d\n", sockfd);
                // //1.单进程单线程
                // Service(sockfd);
                // close(sockfd);
                // 2.多进程
                // pid_t pid = fork();
                // if (pid < 0)
                // {
                //     close(sockfd);
                //     continue;
                // }
                // else if (pid == 0)
                // {
                //     //child
                //     close(_listensock);
                //     if (fork() > 0)//把儿子进程退出，令孙子进程被进程为0的领养
                //         exit(0);
                //     Service(sockfd);
                //     close(sockfd);
                //     exit(0);
                // }
                // 3.线程池
                task_t t = std::bind(&TcpServer::Routine, this, sockfd, InetAddr(client));
                ThreadPool<task_t>::GetInstance()->push(t);
            }
        }
    }

    void RegistrationService(std::string service_name, callback_t func)
    {
        _funcs[service_name] = func;
    }

private:
    int _listensock;
    uint16_t _port;
    bool _isrunning;

    std::unordered_map<std::string, callback_t> _funcs;
};
